package com.oj.judge.service.impl;

import com.oj.judge.domain.Submission;
import com.oj.judge.enums.JudgeResultMessageEnum;
import com.oj.judge.mapper.SubmissionMapper;
import com.oj.judge.service.JudgeService;
import com.oj.judge.service.SubmissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class SubmissionServiceImpl implements SubmissionService {

    @Autowired
    private SubmissionMapper submissionMapper;

    @Autowired
    private JudgeService judgeService; // 判题核心逻辑，异步执行

    @Override
    public Long submitCode(Submission submission) {
        try {
            // 1. 初始化提交状态为 "Pending"
            submission.setStatus(JudgeResultMessageEnum.PENDING.getValue());
            submission.setCreateTime(LocalDateTime.now());
            // 2. 存储提交信息
            submissionMapper.insert(submission);
            Long submissionId = submission.getId();

            // 3. 异步判题
            CompletableFuture.runAsync(() -> {
                try {
                    judgeService.judge(submission);
                } catch (Exception e) {
                    log.error("异步判题时发生错误，submissionId: {}", submissionId, e);
                }
            });

            // 4. 返回提交 ID，用户可通过 ID 轮询查询判题状态
            return submissionId;
        } catch (Exception e) {
            log.error("提交代码时发生错误", e);
            throw new RuntimeException("提交代码时发生错误", e);
        }
    }

    @Override
    public Submission getSubmissionById(Long submissionId) {
        try {
            Submission submission = submissionMapper.selectById(submissionId);
            if (submission == null) {
                log.warn("未找到 submissionId: {}", submissionId);
                throw new IllegalArgumentException("未找到 submissionId: " + submissionId);
            }
            return submission;
        } catch (Exception e) {
            log.error("根据 ID 获取提交信息时发生错误，submissionId: {}", submissionId, e);
            throw new RuntimeException("根据 ID 获取提交信息时发生错误", e);
        }
    }
}
